<template>
  <view class="wh_750 flex flex-column align-center pageHeight bg_F5F5F5">
    <s-header-title ref="headerTitle" isDisplayBack title="添加家谱成员" is-fixed
                    background="#FFFFFF"
                    @getPageHeight="getPageHeight" zIndex="10">
      <template>
        <view class="anniversariesList_headerTitle">
          <text class="anniversariesList_headerTitle_text">{{ page.options.name }}</text>
        </view>
      </template>
    </s-header-title>
    <view :style="{height:`${page.headerHeight}px`}"></view>
    <view class="header flex flex-column align-center">
      <view class="hW_32"></view>
      <scroll-view :scroll-left="familyMembersProfileListScroll.scrollLeft" :scroll-x="true"
                   class="familyMemberPopUp_scrollView"
                   scroll-with-animation>
        <view :id="memberInformation.selectProfileIndex == index ? 'familyMemberPopUp_scrollView_list':''"
              class="familyMemberPopUp_scrollView_list flex flex-column align-center"
              v-for="(item,index) in memberInformation.familyMembersProfileList"
              :style="{
              padding:index == 0 ? '0 24rpx 0 0':index == memberInformation.familyMembersProfileList.length?'0 0 0 24rpx':'0 24rpx'
            }" :key="index" @click="changeTab(index)">
          <image-avater id="imageAvater" :width="memberInformation.selectProfileIndex == index?161 : 108"
                        :height="memberInformation.selectProfileIndex == index? 161 : 108"
                        :src="`${nc_image}${item.avatar}`"
                        :is-order="memberInformation.selectProfileIndex == index"
                        :border-width="8" border-color="#FF4206"></image-avater>
          <view class="familyMemberPopUp_scrollView_list_name flex align-center justify-center mt_20"
                v-if="memberInformation.selectProfileIndex == index && page.options.is_create == 1 && page.options.is_init == 1">
            {{ page.remark || '称谓' }}
          </view>
        </view>
      </scroll-view>
      <view class="hW_50"></view>
      <view class="name flex align-center justify-center">
        <view class="honourableSurname mr_32">
          <input v-model="familyInformation.surname" class="honourableSurname_input"
                 :focus="familyInformation.surnameFocus" placeholder="尊姓"
                 @input="surnameInput" @blur="surnameBlur">
        </view>
        <view class="oneSPersonalName ml_32">
          <input v-model="familyInformation.name" class="oneSPersonalName_input" :focus="familyInformation.nameFocus"
                 placeholder="大名"
                 @input="nameInput" @blur="nameBlur">
        </view>
      </view>
      <view class="hW_20"></view>
    </view>
    <view class="hW_60"></view>
    <gapbar title="生日" @elementClick="setBirthday">
      <template v-slot:content>
        <view class="addRelatives_text flex align-center" v-if="!!familyInformation.solarDate">
          <view>{{ dayjs(familyInformation.solarDate).format('YYYY年MM月DD日') }}</view>
          <view class="ml_15">{{ familyInformation.lunarDate }}</view>
        </view>
      </template>
    </gapbar>
    <view class="hW_20" v-if="!familyInformation.isMore"></view>
    <gapbar title="更多" @elementClick="familyInformation.isMore = true" v-if="!familyInformation.isMore"></gapbar>
    <view class="hW_20" v-if="familyInformation.isMore"></view>
    <gapbar title="祖籍地" @elementClick="openAncestralHome" v-if="familyInformation.isMore">
      <template v-slot:content>
        <view class="addRelatives_text flex flex-column align-end">
          <view>{{ familyInformation.ancestral }}</view>
          <view class="wh_380" style="overflow: hidden;white-space: nowrap;text-overflow: ellipsis;text-align: end">
            {{ familyInformation.ancestral_address }}
          </view>
        </view>
      </template>
    </gapbar>
    <view class="hW_20" v-if="familyInformation.isMore"></view>
    <gapbar title="现居地" @elementClick="openPlaceOfResidence(2)"
            v-if="familyInformation.isMore && !!familyInformation.is_alive">
      <template v-slot:content>
        <view class="addRelatives_text flex align-end flex-column">
          <view>{{ familyInformation.current_residence }}</view>
          <view class="wh_380" style="text-align: end;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
            {{ familyInformation.current_residence_address }}
          </view>
        </view>
      </template>
    </gapbar>
    <view class="hW_20" v-if="familyInformation.isMore"></view>
    <gapbar title="在世" :show-right="false" :showRight="false" v-if="familyInformation.isMore">
      <template v-slot:content>
        <su-switch v-model="familyInformation.is_alive"
                   size="40"
                   :bg="'bg_FF4206'"
                   @change="setAlice($event)"
        ></su-switch>
      </template>
    </gapbar>
    <view class="hW_20" v-if="familyInformation.isMore"></view>
    <gapbar v-if="familyInformation.isMore && !familyInformation.is_alive" title="祭日" @elementClick="setBirthdayDie">
      <template v-slot:content>
        <view class="addRelatives_text flex align-center" v-if="!!familyInformation.solarDate_die">
          <view>{{ dayjs(familyInformation.solarDate_die).format('YYYY年MM月DD日') }}</view>
          <view class="ml_15">{{ familyInformation.lunarDate_die }}</view>
        </view>
      </template>
    </gapbar>
    <view class="hW_20" v-if="familyInformation.isMore"></view>
    <gapbar title="墓地" @elementClick="openPlaceOfResidence(0)"
            v-if="familyInformation.isMore && !familyInformation.is_alive">
      <template v-slot:content>
        <view class="addRelatives_text flex align-end flex-column">
          <view>{{ familyInformation.current_residence }}</view>
          <view class="wh_380" style="text-align: end;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
            {{ familyInformation.current_residence_address }}
          </view>
        </view>
      </template>
    </gapbar>
    <view class="hW_30"></view>
    <view class="flex align-center justify-between wh_362" v-if="page.is_show_old">
      <view :class="familyInformation.selectFlag == 1 ? 'bg_FF4206 color_FFFFFF' : 'bg_FFFFFF color_F5F5F5'"
            class="wh_153 hW_54 flex align-center justify-center fs_24 fw_500" style="border-radius: 32rpx"
            @click.stop="familyInformation.selectFlag = 1"
      >
        比{{ page.is_show_text }}大
      </view>
      <view :class="familyInformation.selectFlag == 2 ? 'bg_FF4206 color_FFFFFF' : 'bg_FFFFFF color_F5F5F5'"
            class="wh_153 hW_54 flex align-center justify-center fs_24 fw_500" style="border-radius: 32rpx"
            @click.stop="familyInformation.selectFlag = 2"
      >
        比{{ page.is_show_text }}小
      </view>
    </view>
    <view class="hW_52"></view>
    <view class="confirm flex align-center justify-center" @click.stop="debounce(confirm,1500,true)">
      完成
    </view>
    <view class="hW_50"></view>
    <!-- 生日 -->
    <s-better-calendar class="z-999" ref="betterCalendarRef" :defaultType="time.defaultType"
                       :defaultValue="time.defaultValue"
                       :showCalendar="time.showCalendar" @confirm="updateMemberBirthday"
                       @cancel="time.showCalendar = false"
    ></s-better-calendar>
    <!-- 祭日 -->
    <s-better-calendar class="z-999" ref="betterCalendarDieRef" :defaultType="time.defaultTypeDie"
                       :defaultValue="time.defaultValueDie"
                       :showCalendar="time.showCalendarDie" @confirm="updateMemberBirthdayDie"
                       @cancel="time.showCalendarDie = false"
    ></s-better-calendar>
    <!-- 选择祖籍地 -->
    <su-region-picker title="选择祖籍地"
                      :show="flag.areaWindowDisplay"
                      @cancel="flag.areaWindowDisplay = false"
                      @confirm="onRegionConfirm"
    ></su-region-picker>
    <!-- 选择现居地 -->
    <su-region-picker title="选择现居地"
                      :show="flag.presentAddress"
                      @cancel="flag.presentAddress = false"
                      @confirm="onAddressConfirm"
    ></su-region-picker>
  </view>
</template>

<script setup>
  import HeaderTitle from '@/pages/genealogy/components/headerTitle.vue';
  import { computed, getCurrentInstance, nextTick, reactive, ref, watch } from 'vue';
  import { onLoad } from '@dcloudio/uni-app';
  import sheep from '@/sheep';
  import ImageAvater from '@/sheep/components/s-avatar/s-avatar.vue';
  import Gapbar from '@/pages/genealogy/components/gapbar.vue';
  import SBetterCalendar from '@/sheep/components/s-better-calendar/s-better-calendar.vue';
  import SuRegionPicker from '@/sheep/ui/su-region-picker/su-region-picker.vue';
  import debounce from '@/sheep/helper/debounce';
  import dayjs from 'dayjs';

  const { proxy } = getCurrentInstance();

  const page = reactive({
    headerHeight: 0,
    options: {},
    is_show_old: false,
    is_show_text: '',
    remark: '',
  });
  const memberInformation = reactive({
    familyMembersProfileList: [],
    selectProfileIndex: 2,
    gxName: '',
  });
  const familyMembersProfileListScroll = reactive({
    scrollLeft: 0,
    width: 0,
    selectWidth: 0,
    allWidth: 0,
  });
  const familyInformation = reactive({
    isMore: false,
    surname: '',
    name: '',
    birthday: '',
    dieday: '',
    ancestral: '',
    current_residence: '',
    is_alive: true,
    isLeapMonth: 1,
    isLeapMonths_die: 1,
    isLeapMonths: 1,
    selectFlag: 1,
    is_lunar_die: 1,
    surnameFocus: false,
    nameFocus: false,
  });
  const time = reactive({
    defaultType: 'solar',
    defaultValue: [100, 0, 0],
    showCalendar: false,
    date: '',
    time: '',
    showCalendarDie: false,
    defaultValueDie: [100, 0, 0],
    defaultTypeDie: 'solar',
  });
  const flag = reactive({
    areaWindowDisplay: false,
  });

  watch(familyMembersProfileListScroll, (newValue, oldValue) => {
    familyMembersProfileListScroll.scrollLeft = newValue.allWidth - newValue.width / 2 + newValue.selectWidth / 2;
  }, { deep: true });
  const nc_image = computed(() => sheep.$store('AI').nc_image);

  onLoad(async (options) => {
    page.options = options;
    if (options.gxname) {
      memberInformation.gxName = options.gxname;
    }
    await getDefaultAvatar();
    // 是否显示大小
    const { data } = await sheep.$api.genealogy.getShowOld({
      genealogy_id: page.options.genealogy_id,
      id: page.options.id,
      val: page.options.val,
    });
    familyInformation.surname = data.surname;
    if (!!familyInformation.surname) {
      familyInformation.nameFocus = true;
    } else {
      familyInformation.surnameFocus = true;
    }
    page.is_show_old = data.is_show_old == 0 ? false : true;
    page.remark = data.remark;
    page.is_show_text = data.is_show_text;
    memberInformation.familyMembersProfileList.forEach((item, index) => {
      if (data.avatar_id == item.id) {
        nextTick(() => {
          memberInformation.selectProfileIndex = index;
          moveTo(index);
        });
      }
    });
  });

  function getPageHeight(number) {
    page.headerHeight = number;
  }

  // 获取默认头像
  async function getDefaultAvatar() {
    const { data } = await sheep.$api.family.getDefaultAvatar({ type: page.options.sex });
    memberInformation.familyMembersProfileList = data;
    memberInformation.familyMembersProfileList.forEach((item, index) => {
      if (page.options.val == item.val) {
        nextTick(() => {
          memberInformation.selectProfileIndex = index;
          // this.moveTo(index);
        });
      }
    });
  }

  function changeTab(index) {
    memberInformation.selectProfileIndex = index;
    setTimeout(() => {
      moveTo(index);
    }, 10);
  }

  function moveTo(index) {
    const query = uni.createSelectorQuery().in(proxy);
    query.select('.familyMemberPopUp_scrollView').boundingClientRect(data => {
      familyMembersProfileListScroll.width = data.width;
    }).exec();
    query.select('#familyMemberPopUp_scrollView_list').boundingClientRect(rect => {
      familyMembersProfileListScroll.selectWidth = rect.width;
    }).exec();
    query.selectAll('.familyMemberPopUp_scrollView_list').boundingClientRect(rect => {
      if (rect.length > 0) {
        familyMembersProfileListScroll.allWidth = 0;
        rect.forEach((item, i) => {
          if (i < index) {
            familyMembersProfileListScroll.allWidth += Number(item.width);
          }
        });
      }
    }).exec();
  }

  function surnameInput(e) {
    const inputType = /[^\u4E00-\u9FA5]/g;
    nextTick(() => {
      // familyInformation.surname = e.detail.value.replace(inputType, '').substring(0, 2);
      familyInformation.surname = e.detail.value.substring(0, 2);
    });
  }

  function surnameBlur(e) {
    const inputType = /[^\u4E00-\u9FA5]/g;
    nextTick(() => {
      // familyInformation.surname = e.detail.value.replace(inputType, '').substring(0, 2);
      familyInformation.surname = e.detail.value.substring(0, 2);
    });
  }

  function nameInput(e) {
    const inputType = /[^\u4E00-\u9FA5]/g;
    nextTick(() => {
      // familyInformation.name = e.detail.value.replace(inputType, '').substring(0, 4);
      familyInformation.name = e.detail.value.substring(0, 4);
    });
  }

  function nameBlur(e) {
    const inputType = /[^\u4E00-\u9FA5]/g;
    nextTick(() => {
      // familyInformation.name = e.detail.value.replace(inputType, '').substring(0, 4);
      familyInformation.name = e.detail.value.substring(0, 4);
    });
  }

  function setBirthday() {
    time.showCalendar = true;
  }

  function setBirthdayDie() {
    time.showCalendarDie = true;
  }

  function updateMemberBirthday(e) {
    console.log(e);
    familyInformation.birthday = e.type == 'solar' ? e.solarDate : e.lunarDateNumber;
    familyInformation.isLeapMonth = e.isLeap ? 2 : 1;
    familyInformation.birthday_type = e.type == 'solar' ? 2 : 1;
    familyInformation.solarDate = e.solarDate;
    familyInformation.lunarDate = e.lunarDate;
    time.showCalendar = false;
  }

  function updateMemberBirthdayDie(e) {
    familyInformation.dieday = e.type == 'solar' ? e.solarDate : e.lunarDateNumber;
    familyInformation.isLeapMonths_die = e.isLeap ? 2 : 1;
    familyInformation.is_lunar_die = e.type == 'solar' ? 2 : 1;
    familyInformation.solarDate_die = e.solarDate;
    familyInformation.lunarDate_die = e.lunarDate;
    time.showCalendarDie = false;
  }

  function openAncestralHome() {
    // flag.areaWindowDisplay = true;
    uni.setStorageSync('createAddress', {
      type: 1,
      info: {
        ancestral: familyInformation.ancestral,
        ancestral_address: familyInformation.ancestral_address,
      },
    });
    sheep.$router.go('/pages/extend/createAddress');
    uni.$on('ancestral', (data) => {
      if (!data) {
        uni.$off('ancestral');
        return;
      }
      console.log(data);
      familyInformation.ancestral = data.info.ancestral;
      familyInformation.ancestral_address = data.info.ancestral_address;
    });
  }

  function openPlaceOfResidence(index = 0) {
    uni.setStorageSync('createAddress', {
      type: index,
      info: {
        current_residence: familyInformation.current_residence,
        current_residence_address: familyInformation.current_residence_address,
      },
    });
    sheep.$router.go('/pages/extend/createAddress');
    uni.$on('current_residence', (data) => {
      if (!data) {
        uni.$off('current_residence');
        return;
      }
      console.log(data);
      familyInformation.current_residence = data.info.current_residence;
      familyInformation.current_residence_address = data.info.current_residence_address;
    });
    // flag.presentAddress = true;
  }

  function onRegionConfirm(e) {
    familyInformation.ancestral = e.province_name + '-' + e.city_name + '-' + e.district_name;
    flag.areaWindowDisplay = false;
  }

  function onAddressConfirm(e) {
    familyInformation.current_residence = e.province_name + '-' + e.city_name + '-' + e.district_name;
    flag.presentAddress = false;
  }

  function setAlice(e) {
    console.log(e);
    familyInformation.is_alive = e;
  }

  async function confirm() {
    if (!familyInformation.surname) {
      uni.showToast({
        title: '请填写您的尊姓 例如：郑',
        icon: 'none',
        duration: 2500,
      });
      return;
    }
    if (!familyInformation.name) {
      uni.showToast({
        title: '请填写您的大名 例如：成功',
        icon: 'none',
        duration: 2500,
      });
      return;
    }
    uni.showLoading({
      title: '正在创建...',
      mask: true,
    });
    const { data, code, msg } = await sheep.$api.genealogy.addTrees({
      val: page.options.val,
      record_id: page.options.id,
      genealogy_id: page.options.genealogy_id,
      sex: memberInformation.familyMembersProfileList[memberInformation.selectProfileIndex].sex,
      head: `${nc_image.value}${memberInformation.familyMembersProfileList[memberInformation.selectProfileIndex].avatar}`,
      name: familyInformation.name,
      surname: familyInformation.surname,
      birthday: familyInformation.birthday,
      // 1: 公历，2：农历
      birthday_type: familyInformation.birthday_type,
      // 是否闰月
      isLeapMonth: familyInformation.isLeapMonth,
      // 祖籍地
      ancestral: familyInformation.ancestral,
      // 祖籍地详细地址
      ancestral_address: familyInformation.ancestral_address,
      // 现居地
      current_residence: familyInformation.current_residence,
      // 现居地详细地址
      current_residence_address: familyInformation.current_residence_address,
      // 婚姻纪念日
      commemoration_day: familyInformation.commemoration_day,
      // 婚姻纪念日是否是闰月
      isLeapMonths: familyInformation.isLeapMonths,
      // 1: 公历，2：农历
      commemoration_type: familyInformation.commemoration_type,
      // 在世
      is_alive: familyInformation.is_alive ? 1 : 2,
      // 大小
      is_older: familyInformation.selectFlag,
      // 死亡日期
      dieday: familyInformation.dieday,
      // 死亡日期是否是闰月
      isLeapMonths_die: familyInformation.isLeapMonths_die,
      // 1: 公历，2：农历
      is_lunar_die: familyInformation.is_lunar_die,
    });
    if (code != 1) {
      sheep.$helper.toast(msg);
      return;
    } else {
      await sheep.$store('family').addGenealogyTree(data.info);
      if (page.options.val == 0 || page.options.val == 1) {
        uni.$emit(`appendMemberWife_${data.info.z_parent_id}`, data.info);
      } else if (page.options.val == -1){
        uni.$emit('addFather', data.info)
        await sheep.$store('family').setGenealogyTreeStatus(true)
        await uni.$emit('changeWidth');
      } else if (page.options.val == 6 || page.options.val == 7) {
        if (!!data.info.z_parent_id) {
          uni.$emit(`appendMemberWife_${data.info.z_parent_id}`, data.info);
        } else {
          uni.$emit('addFather', data.info)
          await sheep.$store('family').setGenealogyTreeStatus(true)
          await uni.$emit('changeWidth');
        }
      }  else {
        uni.$emit(`appendMember_${data.info.z_parent_id}`, data.info);
      }
      uni.$emit('getCanonizationDetail')
    }
    setTimeout(async () => {
      await uni.navigateBack();
      uni.hideLoading();
    }, 100);
  }
</script>


<style scoped lang="scss">
  .header {
    width: 750rpx;
    background: #FFFFFF;
    overflow: hidden;
  }

  .familyMemberPopUp_scrollView {
    width: 750rpx;
    overflow: hidden;
    white-space: nowrap;

    .familyMemberPopUp_scrollView_list {
      display: inline-block !important;

      .familyMemberPopUp_scrollView_list_name {
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 30rpx;
        color: #FF4206;
      }
    }
  }

  .name {
    .honourableSurname {
      .honourableSurname_input {
        width: 300rpx;
        height: 80rpx;
        background: #F8F8F8;
        border-radius: 40rpx 40rpx 40rpx 40rpx;
        overflow: hidden;
        text-align: center;
        font-size: 36rpx;
        font-weight: bold;
      }
    }

    .oneSPersonalName {
      .oneSPersonalName_input {
        width: 300rpx;
        height: 80rpx;
        background: #F8F8F8;
        border-radius: 40rpx 40rpx 40rpx 40rpx;
        text-align: center;
        font-size: 36rpx;
        font-weight: bold;
      }
    }
  }

  .confirm {
    width: 362rpx;
    height: 80rpx;
    background: #FF4206;
    border-radius: 41rpx 41rpx 41rpx 41rpx;
    font-family: PingFang SC, PingFang SC;
    font-weight: 500;
    font-size: 30rpx;
    color: #FFFFFF;
  }

  .anniversariesList_headerTitle {
    position: absolute;
    bottom: -26rpx;
    left: 50%;
    transform: translateX(-50%);

    .anniversariesList_headerTitle_text {
      font-family: PingFang SC, PingFang SC;
      // font-weight: 500;
      font-size: 20rpx;
      color: rgba(0, 0, 0, 0.2);
    }
  }

  .addRelatives_text {
    font-size: 30rpx;
    font-weight: 500;
  }
</style>
